package org.example.servlet;

import org.example.dao.UserDAO;
import org.example.dao.UserDAOImpl;
import org.example.model.User;
import org.json.JSONObject;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;

@WebServlet("/register")
public class RegisterServlet extends HttpServlet {
    private UserDAO userDAO = new UserDAOImpl();
    
    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response) 
            throws ServletException, IOException {
        response.setContentType("application/json;charset=UTF-8");
        PrintWriter out = response.getWriter();
        JSONObject result = new JSONObject();
        
        try {
            // 获取表单数据
            String username = request.getParameter("username");
            String password = request.getParameter("password");
            String email = request.getParameter("email");
            String phone = request.getParameter("phone");
            
            // 创建用户对象
            User user = new User();
            user.setUsername(username);
            user.setPassword(password); // 实际应用中应该加密
            user.setEmail(email);
            user.setPhone(phone);
            
            // 检查用户名是否已存在
            if (userDAO.findByUsername(username) != null) {
                result.put("success", false);
                result.put("message", "用户名已存在");
                out.print(result.toString());
                return;
            }
            
            // 保存用户
            boolean success = userDAO.save(user);
            
            if (success) {
                result.put("success", true);
                result.put("message", "注册成功");
            } else {
                result.put("success", false);
                result.put("message", "注册失败，请重试");
            }
            
        } catch (Exception e) {
            result.put("success", false);
            result.put("message", "注册失败：" + e.getMessage());
            e.printStackTrace();
        }
        
        out.print(result.toString());
    }
    
    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response) 
            throws ServletException, IOException {
        // 处理检查用户名是否可用的请求
        if (request.getPathInfo() != null && request.getPathInfo().equals("/checkUsername")) {
            response.setContentType("application/json;charset=UTF-8");
            PrintWriter out = response.getWriter();
            JSONObject result = new JSONObject();
            
            String username = request.getParameter("username");
            boolean isAvailable = userDAO.findByUsername(username) == null;
            
            result.put("available", isAvailable);
            out.print(result.toString());
        }
    }
} 